#  -*- coding: utf-8 -*-

from pymongo import UpdateOne,ASCENDING, DESCENDING
from monitor.base_monitor import BaseMonitor
from data.finance_report_crawler import FinanceReportCrawler
from data.data_module import DataModule
from util.stock_util import get_all_trading_codes_data_trading_date,get_all_codes,get_all_indexes_date,calc_negative_diff_dates,multi_computer,get_code_name,get_trading_dates,get_diff_dates,get_sub_industry
from util.database import DB_CONN
import time
import pandas as pd
from datetime import datetime, timedelta
from factor.factor_module import FactorModule
from pathlib import Path
import numpy as np
"""
实现对当前大盘状态的分析，判断是否适合做交易
"""


class TradeFitMonitor(BaseMonitor):
    def __init__(self):
        BaseMonitor.__init__(self, name='trade_fit')
        self.collection = DB_CONN['trade_fit']
        self.collection.create_index([('date', 1)])

    def monitoring(self, begin_date, end_date):
        dm = DataModule()
        fm = FactorModule()
        """
        计算大盘是否适合交易的相关指标
        """
        code = '999999'
        begin_date = '2018-01-01'
        #end_date = '2021-06-25'

        if end_date is None:
            end_date = datetime.now().strftime('%Y-%m-%d')

        dates = get_trading_dates(begin_date,end_date)
        result_df = pd.DataFrame(columns=('close','total_amount','stock_nums','avg_amount'),index=dates)
        #pre_begin_date = calc_negative_diff_dates(code,is_index=False,date=begin_date, delta_days=-1)
        df_daily = dm.get_k_data(code, index=True, autype='qfq', begin_date=begin_date, end_date=end_date)
        df_daily.set_index(['date'], inplace=True)
        result_df['close'] = df_daily['close']

        for date in dates:
            t1 = time.time()
            num, amount = get_all_trading_codes_data_trading_date(date)
            result_df.loc[date,'stock_nums'] = num
            result_df.loc[date,'total_amount'] = amount
            result_df.loc[date,'avg_amount'] = round(amount/num,2)

            fm_date_df = fm.get_single_date_factors("rs", False, date)
            #hfq计算rs过程中，有除0行为，产生inf数据，替换为0
            fm_date_df = fm_date_df.replace([np.inf, -np.inf], 0)
            # Step1 取20日RS大于87的个股排名,rs_120>0代表上市超过半年（超过半年才有rs_120的数据）
            rs_df = fm_date_df.loc[(fm_date_df['rs_20'] >= 87) & (fm_date_df['rs_120'] >= 0)]
            result_df.loc[date, 'rs_20_gt87_avg_change_rate'] = round(rs_df['rs_change_rate_20'].mean(),2)
            result_df.loc[date, 'rs_20_gt87_avg_amount'] = round(rs_df['rs_mean_amount_20'].mean(),2)
            result_df.loc[date, 'rs_20_gt87_median_change_rate'] = rs_df.median(skipna  =  True)['rs_change_rate_20']
            result_df.loc[date, 'rs_20_gt87_median_amount'] = rs_df.median(skipna  =  True)['rs_mean_amount_20']

            #取RS20小于50的个股信息，用于判断是否主跌，具备明显的亏钱效应
            rs_df = fm_date_df.loc[(fm_date_df['rs_20'] <= 50) & (fm_date_df['rs_120'] >= 0)]
            result_df.loc[date, 'rs_20_lt50_avg_change_rate'] = round(rs_df['rs_change_rate_20'].mean(),2)
            result_df.loc[date, 'rs_20_lt50_avg_amount'] = round(rs_df['rs_mean_amount_20'].mean(),2)

            t2 = time.time()
            print(f"date:{date} 计算用时：{round(t2-t1,2)}秒")
        print(result_df.tail())
        result_df.to_csv(f"大盘是否适合做交易分析_{begin_date}-{end_date}.csv")


        return

if __name__ == '__main__':
    # 执行因子的提取任务
    #hfq =HfqMAFactor()
    pd.set_option('display.width',500)
    pd.set_option('display.max_columns', 500)
    pd.set_option('display.max_colwidth', 500)
    TradeFitMonitor().monitoring('2021-09-02', None)
